import React, { useState } from 'react';
import './App.css';
import { isObjectValuesEmpty } from "./tools/index";

type TableCloumn = {
  id: number;
  name: string;
  image: string;
  color: string;
  quantity: number;
  createdAt: string;
  modifiedAt: string;
}

const TableTh: React.FC<{
  name: string;
}> = (props) => {
  return <th>{props.name}</th>
}

const TableTd: React.FC<{
  value: string | number;
}> = (props) => {
  return <td>{props.value}</td>
}

const App: React.FC<{}> = () => {

  const [materials, setMaterials] = useState<TableCloumn[]>([
    { id: 1, name: 'Material 1', image: 'image1.jpg', color: 'red', quantity: 10, createdAt: '2024-01-01', modifiedAt: '2024-01-01' },
    { id: 2, name: 'Material 2', image: 'image2.jpg', color: 'blue', quantity: 20, createdAt: '2024-01-02', modifiedAt: '2024-01-02' },
  ]);
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [dialog, setDialog] = useState<boolean>(false);

  const [editMaterial, setEditMaterial] = useState<TableCloumn>({
    id: 0,
    name: '',
    image: '',
    color: '',
    quantity: 0,
    createdAt: '',
    modifiedAt: '',
  });

  // 查询事件
  const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(event.target.value);
  };

  // 重置事件
  const resetSearch = () => {
    setSearchTerm('');
  };

  // 添加/编辑事件
  const handleMaterialSubmit = () => {
    if (editMaterial.id !== 0) {
      void saveEditedMaterial();
    } else {
      void handleAddMaterial();
    }
  }

  // 添加事件
  const handleAddMaterial = () => {
    const nowDate = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
    const newMaterial = {
      ...editMaterial,
      id: materials.length + 1,
      createdAt: nowDate,
      modifiedAt: nowDate
    };
    if (isObjectValuesEmpty(newMaterial)) {
      alert("请填写完整信息。");
      return false;
    }
    setMaterials([...materials, newMaterial]);
    void resetDialog();
  };

  // 编辑事件
  const handleEditMaterial = (material: TableCloumn) => {
    setEditMaterial(material);
    setDialog(true)
  };

  // dialog重置事件
  const resetDialog = () => {
    setEditMaterial({
      id: 0,
      name: '',
      image: '',
      color: '',
      quantity: 0,
      createdAt: '',
      modifiedAt: '',
    })
    setDialog(false)
  }

  // 删除事件
  const handleDeleteMaterial = (id: number) => {
    setMaterials(prevState =>
      prevState.filter(material => material.id !== id)
    );
  };

  // 保存事件
  const saveEditedMaterial = () => {
    const updatedMaterials = materials.map(item =>
      item.id === editMaterial.id ? editMaterial : item
    );
    setMaterials(updatedMaterials);
    setEditMaterial({
      id: 0,
      name: '',
      image: '',
      color: '',
      quantity: 0,
      createdAt: '',
      modifiedAt: '',
    });
    void resetDialog()
  };

  const filteredMaterials = materials.filter(material =>
    material.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div>
      <input type="text" placeholder="Search by name" value={searchTerm} onChange={handleSearch} />
      <button onClick={resetSearch}>重置</button>
      <button onClick={() => setDialog(true)}>添加</button>
      <table>
        <thead>
          <tr>
            <TableTh name="ID" />
            <TableTh name="Name" />
            <TableTh name="Image" />
            <TableTh name="Color" />
            <TableTh name="Quantity" />
            <TableTh name="Created At" />
            <TableTh name="Modified At" />
            <TableTh name="Actions" />
          </tr>
        </thead>
        <tbody>
          {filteredMaterials.map(material => (
            <tr key={material.id}>
              <TableTd value={material.id} />
              <TableTd value={material.name} />
              <TableTd value={material.image} />
              <TableTd value={material.color} />
              <TableTd value={material.quantity} />
              <TableTd value={material.createdAt} />
              <TableTd value={material.modifiedAt} />
              <td>
                <button onClick={() => handleEditMaterial(material)}>编辑</button>
                <button onClick={() => handleDeleteMaterial(material.id)}>删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {
        dialog &&
        <div>
          <h2>{editMaterial.id !== 0 ? '编辑' : '添加'}</h2>
          <input type="text" placeholder="Name" value={editMaterial.name} onChange={(e) => setEditMaterial({ ...editMaterial, name: e.target.value })} />
          <input type="text" placeholder="Image" value={editMaterial.image} onChange={(e) => setEditMaterial({ ...editMaterial, image: e.target.value })} />
          <input type="text" placeholder="Color" value={editMaterial.color} onChange={(e) => setEditMaterial({ ...editMaterial, color: e.target.value })} />
          <input type="number" placeholder="Quantity" value={editMaterial.quantity} onChange={(e) => setEditMaterial({ ...editMaterial, quantity: parseInt(e.target.value) })} />
          <button onClick={handleMaterialSubmit}>{editMaterial.id !== 0 ? '保存' : '添加'}</button>
        </div>
      }
    </div>
  );
}

export default App;
